package com.filldream.fastboot.core.manager;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.filldream.fastboot.base.entity.SysDept;
import com.filldream.fastboot.base.mapper.SysDeptMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class DeptManager {

    @Resource
    private SysDeptMapper baseMapper;


    public Long getParentCompanyId(Long deptId) {
        if( deptId == null || deptId.equals(0L)){
            return 0L;
        }

        SysDept sysDept = baseMapper.selectById(deptId);

        //如果选择的是公司，则为本身
        if( sysDept.getDeptType().equals(1) ){
            return deptId;
        }

        List<SysDept> resultList  = baseMapper.selectList( new QueryWrapper<SysDept>().eq("del_flag",0));
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setChildrenKey("children");
        treeNodeConfig.setIdKey("deptId");
        List<Tree<String>> treeNodes = TreeUtil.build(resultList, sysDept.getParentId()+"", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getParentId()+"");
                    tree.setParentId(treeNode.getDeptId()+"");
                    tree.putExtra("deptType",treeNode.getDeptType());
                    tree.putExtra("deptName",treeNode.getDeptName());
                });
        return Long.valueOf(getParentCompanyId(treeNodes));
    }

    public String getParentCompanyId(List<Tree<String>> treeNodes){
        for (Tree<String> item : treeNodes) {
            if(item.get("deptType").equals(1)){
                return item.getParentId();
            }else{
                return getParentCompanyId(item.getChildren());
            }
        }
        return "0";
    }

}
